package com.deanlib.cabinet.data.network.intercept;

import com.deanlib.cabinet.data.network.annotation.DynamicTimeout;
import com.elvishew.xlog.XLog;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Invocation;

/**
 * Created by Dean on 2022/12/24
 */
public class DynamicAnnotationInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        final Invocation tag = request.tag(Invocation.class);
        final Method method = tag != null ? tag.method() : null;
        final DynamicTimeout timeout = method != null ? method.getAnnotation(DynamicTimeout.class) : null;

        XLog.d("invocation",tag!= null ? tag.toString() : "");

        if(timeout !=null && timeout.value() > 0){
            Response proceed = chain.withConnectTimeout(timeout.connectTimeout()>0?timeout.connectTimeout():timeout.value(), TimeUnit.MILLISECONDS)
                    .withReadTimeout(timeout.readTimeout()>0?timeout.readTimeout():timeout.value(), TimeUnit.MILLISECONDS)
                    .withWriteTimeout(timeout.writeTimeout()>0?timeout.writeTimeout():timeout.value(), TimeUnit.MILLISECONDS)
                    .proceed(request);
            return proceed;
        }

        return chain.proceed(request);
    }
}
